/**
 * Created by fsj on 2017/6/8.
 */
function setupWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) {
        return callback(WebViewJavascriptBridge);
    } else {
        document.addEventListener('WebViewJavascriptBridgeReady',
            function () {
                callback(WebViewJavascriptBridge)
            }, false
        )
    }

    if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
        if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
        }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function () {
            document.documentElement.removeChild(WVJBIframe);
        }, 0);
    }
}

export default  {
    registerRefreshData: function (vm) {
        setupWebViewJavascriptBridge(function (bridge) {
            bridge.registerHandler('refreshData', function (data, responseCallback) {
                if (vm.$children[0].refreshData && typeof vm.$children[0].refreshData === 'function') {
                    vm.$children[0].refreshData(responseCallback);
                } else {
                    setTimeout(function () {
                        window.location.reload();
                    }, 100);
                    responseCallback({code: '0'});
                }
            })
        });
    }
};
